import { gcfg } from "../../../gcfg"
import QWEventDispatcher from "../../GMDBase/QWEventDispatcher"
import QWEvent from "../../GMDBase/QWEvent"
import LCData from "../../GMDWeakNetGameBase/LCData";
import Login from "../../GMDWeakNetGameBase/Login";
import GameConn from "../../GMDWeakNetGameBase/GameConn";
import NSLoader from "../../GMDWeakNetGameBase/NSLoader";
import LocalResources from "../../GMDCocosBase/LocalResources";
import SDataInvite from "./SDataInvite";
import { MD } from "../../GMDBase/MD"; 
import fbAccount from "../fbAccount";
import FB from "../FB";

/*
I16$ShareTarget	
0=无限制
1=个人和群（不区分群id）
2=个人和群（每个群单独记次）
3=仅群（不区分群id）
4-仅群（每个群单独记次）  
*/

let g_Shareing = false//当前是否处于分享中
let canvas = null;
function getImgBase64(_texture:cc.Texture2D) {
    let width = 600, height = 315;
    if(!canvas) canvas = document.createElement('canvas');
    let ctx = canvas.getContext('2d');
    canvas.width = width;
    canvas.height = height;
    let image = _texture.getHtmlElementObj();
    ctx.drawImage(image, 0, 0);
   
    return canvas.toDataURL('image/png');
}


function GetShareImgAndText(row) {
    var imgBase64
    var title

    //存在重定向文案接口
    if (InviteFriends.RedirectImgAndText) {
        var obj = InviteFriends.RedirectImgAndText(row[SDataInvite.Singletion.FD.I_ShareChannel])
        if (obj)//返回了重定向的文案
        {
            //返回的图片地址有效
            if (obj.imgUrl) imgBase64 = obj.imgBase64

            //返回的标题有效
            if (obj.title) title = obj.title
        }
    }

    //重定向失败时，应用原规则
    if (!imgBase64) 
    { 
    //imgUrl = StringEX.MergePath(MD.ServerList.ArticleSvr, row[SDataShare.Singletion.FD.I_Icon])
        imgBase64 = getImgBase64( LocalResources.Singletion.GetRes( row[SDataInvite.Singletion.FD.I_Icon] ).getTexture() )
    }

    if (!title) title = row[SDataInvite.Singletion.FD.I_Note]

    return {
        imgBase64: imgBase64,
        title: title
    }
}



//分享管理器
export default class InviteFriends {
    //分享错误事件
    public static EVT_SHARE_ERROR = "EvtShareError"

    //分享管理器开始工作
    public static Go() { 
 
    }

 

    //主动弹出分享
    public static OpenShare(channelId: number, query: any = null) {
        cc.log("主动弹出分享");
        FB.logEvent("all_tl_share_click",1,{})
        
        
        var shareNum = InviteFriends.GetAllShareNum(channelId)
        var row = SDataInvite.Singletion.GetShareRow(channelId, shareNum)

        var imgTxt = GetShareImgAndText(row)
        cc.log("开始分享事件");
         

        g_Shareing = true

         
/*
        var success = (res) => {
            if(!g_Shareing) return
            g_Shareing = false
            InviteFriends.DoShareSuccess(res, row)
        }
        var fail = (res) => {
            if(!g_Shareing) return
            
            g_Shareing = false
            //errMsg 
            console.log("分享失败", res)

            if (
                res.errMsg != "shareAppMessage:fail cancel" &&
                res.errMsg != "shareAppMessage:cancel"
            )
            InviteFriends.PostErrorEvt(
                    channelId,
                    false,
                    InviteFriends.ERR_NO.UnknownError
                )
        }
 */

        FB.shareAsync({
            intent: 'SHARE',
            image: imgTxt.imgBase64,// getImgBase64(texture),
            text: imgTxt.title,
            data: query?query:{},
        })
        .then(function () {
            cc.log('FB分享完成');
        });

    }

    //当前是否处于分享状态
    public static get Shareing(): boolean { return g_Shareing; }

    //重定向分享图文
    //入口参数: Func(shareChannel:number)
    //
    //重定向失败时，应返回 null
    //
    //重定向成功时候，应返回
    //{
    //    imgUrl:<图片地址>,
    //    title:<标题>
    //}
    public static RedirectImgAndText: Function

    //注册功能
    public static RegFunc(funcNum, func, owner = null) {
        InviteFriends.m_FuncCallbacks[funcNum] = [func, owner]
    }

    //错误号枚举
    public static ERR_NO = {
        MustShareToGroup: 0,//要求分享到群，实际却没有 
        TooMany: 2, //分享次数太多，已经没有奖励可领取了
        UnknownError: 3 //未知错误
        // RepeatedSharing：4
    };

    //监听事件
    public static addEventListener(type: string, listener, owner = null) {
        InviteFriends.m_Evts.addEventListener(type, listener, owner)
    }

    //参数对象转换为字符串形式
    static Query2Str(query: any): string {
        if (!query) return ""
        var re = ""
        for (var k in query) {
            var v = query[k]
            var str = k + "=" + v
            if (re == "")
                re = str
            else
                re += "&" + str
        }
        return re
    }


    //抛出错误事件
    static PostErrorEvt(channelId: number, isShareToGroup: boolean, errNo: number, exAttrs: any = null) {
        var evt = new QWEvent(InviteFriends.EVT_SHARE_ERROR)
        evt.details = {
            channelId: channelId,//分享口ID
            errNo: errNo,//错误号
            isShareToGroup: isShareToGroup,//用户实际是否是分享给群了
        }

        //填充扩展属性
        if (exAttrs) {
            for (var k in exAttrs) evt.details[k] = exAttrs[k]
        }

        InviteFriends.m_Evts.dispatchEvent(evt)
    }


    //执行功能
    static DoFunc(funcNum, obj: any) {
        var funcInfo = InviteFriends.m_FuncCallbacks[funcNum]
        if (!funcInfo) return

        if (funcInfo[1])//存在owner
            funcInfo[0].call(funcInfo[1], obj)
        else
            funcInfo[0](obj)
    }




    //执行分享成功的逻辑
    static DoShareSuccess(res, row) {
        /*
        console.log("分享成功", res)
        var isShareToGroup: boolean = res.shareTickets ? true : false//是否是分享到群
        var shareTarget = row[SDataShare.Singletion.FD.I_ShareTarget]
        var shareChannel = row[SDataShare.Singletion.FD.I_ShareChannel]
        if (
            (shareTarget == 3 || shareTarget == 4) &&//仅分享到群
            !isShareToGroup//实际没有分享到群
        ) { 
            console.log("要求分享到群，实际却没有")
            InviteFriends.PostErrorEvt(
                shareChannel,
                isShareToGroup,
                InviteFriends.ERR_NO.MustShareToGroup
            )
            return
        }


        if (
            isShareToGroup &&//实际是分享到群的 
            (
                shareTarget == 2 || shareTarget == 4//需要区分群id  
            )
        ) {
            //获取群id
            for (var k in res.shareTickets) {
                var shareTicket = res.shareTickets[k]
                wx.getShareInfo(
                    {
                        shareTicket: shareTicket,
                        success: (res) => {
                            if (!MD.SessionKey)//当前没有获取到sessionKey
                            {
                                console.log("尚未登陆成功，无法解密数据")

                                InviteFriends.PostErrorEvt(
                                    shareChannel,
                                    isShareToGroup,
                                    InviteFriends.ERR_NO.UnknownError
                                )
                                return
                            }

                            //解密群id
                            var jsonDoc = Authorize.Decryption(res.encryptedData, res.iv, MD.SessionKey)
                            if (!jsonDoc) {
                                console.log("解密失败！")
                                InviteFriends.PostErrorEvt(
                                    shareChannel,
                                    isShareToGroup,
                                    InviteFriends.ERR_NO.UnknownError
                                )
                                return
                            }

                            var gid: string = jsonDoc.openGId

                            //执行分享成功功能
                            InviteFriends.DoShareFunc(shareTicket, gid, row)
                        },
                        fail: (res) => {
                            console.log("获取群信息失败", res)
                            InviteFriends.PostErrorEvt(
                                shareChannel,
                                isShareToGroup,
                                InviteFriends.ERR_NO.UnknownError
                            )
                        }
                    }
                )
            }

            return
        }

        var shareTick = null
        if (res.shareTickets) {
            for (var kk in res.shareTickets) shareTick = res.shareTickets[kk]
        }
        //执行分享成功的功能
        InviteFriends.DoShareFunc(shareTick, null, row)
        */
    }

    static DoShareFunc(shareTicket: string, groupId: string, row) {
        var isShareToGroup = shareTicket ? true : false
        var shareChannel = row[SDataInvite.Singletion.FD.I_ShareChannel]
        var num = InviteFriends.GetShareNum(groupId, shareChannel)

        //检查是否需要重新根据次数选择行
        var NumType = row[SDataInvite.Singletion.FD.I_NumType]//分享口类型
        if (NumType == 1)//根据分享次数
        {
            row = SDataInvite.Singletion.GetShareRow(shareChannel, num)
        }

        var func = row[SDataInvite.Singletion.FD.I_ShareFunc]

        //记录分享次数 
        num++

        var saveChannel = SDataInvite.Singletion.GetSaveChannel(shareChannel) 

        if (groupId) {
            var scInfo = MD.LCData.GetJson("ShareGroup_" + saveChannel)
            scInfo[groupId] = num
            MD.LCData.SetJson("ShareGroup_" + saveChannel, scInfo)
        } else {
            MD.LCData.Set("Share_" + saveChannel, num)
        }

        var numOfTimes = SDataInvite.Singletion.GetShareTotalNum(shareChannel)
        if (
            NumType == 1 &&//根据分享次数分享
            num > numOfTimes
        )
        { 
            InviteFriends.PostErrorEvt(
                row[SDataInvite.Singletion.FD.I_ShareChannel],
                isShareToGroup,
                InviteFriends.ERR_NO.TooMany,
                {
                    numOfTimes: numOfTimes,//本日分享上限
                    dailyNum: num,//本日实际分享次数
                }
            )
            return
        }

        if (func > 0)//存在附加功能
        {
            if (isShareToGroup)//分享到群了
            InviteFriends.DoFunc(
                    func,
                    {
                        param: row[SDataInvite.Singletion.FD.I_Param],//功能参数
                        dailyNum: num,//今日已经分享的次数
                        shareTicket: shareTicket,//群Ticket
                        groupId: groupId,//群ID
                    }
                )
            else//分享到个人了
            InviteFriends.DoFunc(
                    func,
                    {
                        param: row[SDataInvite.Singletion.FD.I_ParamSingle],//功能参数
                        dailyNum: num,//今日已经分享的次数
                    }
                )
        }
        else //无附加功能
        {
            cc.log("分享完成，无附加功能", shareChannel, shareTicket, num)
        }
    }

    //获取某个分享口实际已经分享的次数
    static GetShareNum(groupId: string, shareChannel: number): number {
        var saveChannel = SDataInvite.Singletion.GetSaveChannel(shareChannel) 

        if (groupId) {
            var scInfo = MD.LCData.GetJson("ShareGroup_" + saveChannel)
            if (!scInfo[groupId]) return 0
            return scInfo[groupId]
        } else {
            return MD.LCData.GetNumber("Share_" + saveChannel)
        }
    }

    //获取某个分享口当日实际分享次数，个人加所有群
    static GetAllShareNum(shareChannel: number): number {
        var saveChannel = SDataInvite.Singletion.GetSaveChannel(shareChannel) 
        var sum = MD.LCData.GetNumber("Share_" + saveChannel)
        var scInfo = MD.LCData.GetJson("ShareGroup_" + saveChannel)
        for (var k in scInfo) sum += scInfo[k]
        return sum
    }

    static m_FuncCallbacks: any = {}
    static m_PageShareRow: any
    static m_PageShareQuery: any
    static m_PageChannelSetup: boolean
    static m_PageChannelVisible: boolean
    static m_Evts: QWEventDispatcher = new QWEventDispatcher()
}
/*
//页面分享口被点击
if (window["wx"]) {
    wx.onShareAppMessage(
        () => {
            var row = InviteFriends.m_PageShareRow

            var imgTxt = GetShareImgAndText(row)

            g_Shareing = true

            var success = (res: any) => {
                if(!g_Shareing) return

                g_Shareing = false
                InviteFriends.DoShareSuccess(res, row)
            }
            var fail = (res: any) => {
                if(!g_Shareing) return

                g_Shareing = false
            }

            WhenOpenShare(success,fail)
            
            return {
                title: imgTxt.title,
                imageUrl: imgTxt.imgUrl,
                query: InviteFriends.Query2Str(InviteFriends.m_PageShareQuery),
                success:success,
                fail:fail
            }

        }
    )
}*/

//1号功能为加金币，直接实现在底层框架
InviteFriends.RegFunc(
    1,
    (obj: any) => {
        var currGold = MD.LCData.GetNumber(MD.LCData.ParamName.GOLD)
        MD.LCData.Set(MD.LCData.ParamName.GOLD, currGold + obj.param)
    }
)

MD.InviteFriends = InviteFriends